package com.smart.translator.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;
import androidx.core.app.NotificationCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import com.smart.translator.MainActivity;
import com.smart.translator.R;
import com.smart.translator.util.VoskSpeechRecognizer;
import android.content.BroadcastReceiver;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Looper;

/**
 * Vosk语音识别服务
 * 应用启动时自动加载模型并开始识别
 */
public class VoskSpeechService extends Service {
    private static final String TAG = "VoskSpeechService";
    
    private VoskSpeechRecognizer voskRecognizer;
    private boolean isModelLoaded = false;
    private boolean isRecognitionStarted = false;
    
    // TTS状态监听
    private BroadcastReceiver ttsStateReceiver;
    private boolean isTtsPlaying = false;
    private boolean isVadEnabled = true; // 新增：VAD检测开关
    
    // 前台服务相关
    private static final String CHANNEL_ID = "vosk_speech_service";
    private static final int NOTIFICATION_ID = 1001;
    
    // 模型路径
    private static final String SMALL_MODEL_PATH = "vosk-model-small-cn-0.22";
    private static final String SMALL_MODEL_ZIP_PATH = "vosk-model-small-cn-0.22.zip";
    private static final String MODEL_PATH = "vosk-model-cn-0.22";
    private static final String MODEL_ZIP_PATH = "vosk-model-cn-0.22.zip";
    
    private BroadcastReceiver vadAudioSourceReceiver;
    
    @Override
    public void onCreate() {
        super.onCreate();
    Log.d(TAG, "VoskSpeechService onCreate 开始");

    // ❶ 无论 API 级别，先创建通知渠道（必须在任何 NotificationBuilder 之前）
    createNotificationChannel();

    // Android 14 及以上使用快速前台服务启动
    if (Build.VERSION.SDK_INT >= 34) {
        try {
            Log.d(TAG, "Android 14+ 快速启动前台服务...");
            Notification simpleNotification = createSimpleNotification("Vosk语音识别服务启动中...");
            startForeground(
                NOTIFICATION_ID,
                simpleNotification,
                android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE
            );
            Log.d(TAG, "✅ Android 14+ 前台服务快速启动成功");
        } catch (Exception e) {
            Log.e(TAG, "❌ Android 14+ 前台服务快速启动失败", e);
            // ❷ 一旦 startForeground() 失败，立刻停掉服务，避免 5s 超时崩溃
            stopSelf();
            return;
        }

        // 后续异步更新完整通知（保持原有逻辑）
        new Thread(() -> {
            try {
                createNotificationChannel();
                Log.d(TAG, "通知渠道创建成功");
                new Handler(Looper.getMainLooper()).post(() -> {
                    try {
                        Notification fullNotification = createNotification("Vosk语音识别服务运行中");
                        NotificationManager notificationManager = getSystemService(NotificationManager.class);
                        if (notificationManager != null) {
                            notificationManager.notify(NOTIFICATION_ID, fullNotification);
                        }
                        Log.d(TAG, "通知已更新为完整版本");
                    } catch (Exception e) {
                        Log.e(TAG, "更新通知失败", e);
                    }
                });
            } catch (Exception e) {
                Log.e(TAG, "后台创建通知渠道失败", e);
            }
        }).start();

    } else {
        // Android 13 以下保持原来两步走（先建渠道，再前台启动）
        try {
            createNotificationChannel();
            Log.d(TAG, "通知渠道创建成功");
        } catch (Exception e) {
            Log.e(TAG, "创建通知渠道失败", e);
        }

        try {
            Log.d(TAG, "准备启动前台服务...");
            Notification notification = createNotification("Vosk语音识别服务启动中...");
            Log.d(TAG, "通知创建成功");

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                startForeground(
                    NOTIFICATION_ID,
                    notification,
                    android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE
                );
            } else {
                startForeground(NOTIFICATION_ID, notification);
            }
            Log.d(TAG, "✅ Vosk前台服务启动成功");
        } catch (Exception e) {
            Log.e(TAG, "❌ 启动前台服务失败", e);
            stopSelf();
            return;
        }
    }

    // 后续注册 TTS 监听、初始化识别器等保持原样...
    try {
        registerTtsStateReceiver();
        Log.d(TAG, "TTS状态监听器注册成功");
    } catch (Exception e) {
        Log.e(TAG, "注册TTS状态监听器失败", e);
    }

    new Thread(() -> {
        try {
            Log.d(TAG, "开始初始化Vosk识别器");
            initVoskRecognizer();
            Log.d(TAG, "Vosk识别器初始化完成");
            new Handler(Looper.getMainLooper()).post(() -> {
                try {
                    autoLoadModel();
                } catch (Exception e) {
                    Log.e(TAG, "自动加载模型失败", e);
                    updateNotification("模型加载失败: " + e.getMessage());
                }
            });
        } catch (Exception e) {
            Log.e(TAG, "初始化Vosk识别器失败", e);
            new Handler(Looper.getMainLooper()).post(() -> {
                updateNotification("初始化失败: " + e.getMessage());
            });
        }
    }).start();

    // 注册VAD音源切换广播（LocalBroadcastManager）
    vadAudioSourceReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (com.smart.translator.ble.AudioProcessor.ACTION_PAUSE_VOSK_VAD.equals(action)) {
                if (voskRecognizer != null) {
                    voskRecognizer.setAudioSource(com.smart.translator.util.VoskSpeechRecognizer.AUDIO_SOURCE_DEFAULT);
                    Log.d(TAG, "收到首帧，切换音源为AUDIO_SOURCE_DEFAULT");
                    stopRecognition();
                }
            } else if (com.smart.translator.ble.AudioProcessor.ACTION_RESUME_VOSK_VAD.equals(action)) {
                if (voskRecognizer != null) {
                    voskRecognizer.setAudioSource(com.smart.translator.util.VoskSpeechRecognizer.AUDIO_SOURCE_MIC);
                    Log.d(TAG, "恢复前切回音源为AUDIO_SOURCE_MIC");
                    autoStartRecognition();
                }
            }
        }
    };
    IntentFilter vadAudioSourceFilter = new IntentFilter();
    vadAudioSourceFilter.addAction(com.smart.translator.ble.AudioProcessor.ACTION_PAUSE_VOSK_VAD);
    vadAudioSourceFilter.addAction(com.smart.translator.ble.AudioProcessor.ACTION_RESUME_VOSK_VAD);
    LocalBroadcastManager.getInstance(this).registerReceiver(vadAudioSourceReceiver, vadAudioSourceFilter);

    Log.d(TAG, "VoskSpeechService onCreate 完成");
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "VoskSpeechService onStartCommand");
        
        // 如果是重新启动的服务，重新开始识别
        if (isModelLoaded && !isRecognitionStarted) {
            Log.d(TAG, "服务重启，重新开始识别");
            autoStartRecognition();
        }
        
        return START_STICKY; // 服务被杀死后自动重启
    }
    
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    
    /**
     * 创建通知渠道（Android 8.0+）
     */
    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                CHANNEL_ID,
                "Vosk语音识别服务",
                NotificationManager.IMPORTANCE_LOW
            );
            channel.setDescription("用于保持Vosk语音识别服务在后台运行");
            channel.setShowBadge(false);
            channel.setSound(null, null);
            
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            if (notificationManager != null) {
                notificationManager.createNotificationChannel(channel);
            }
        }
    }
    
    /**
     * 创建前台服务通知
     */
    private Notification createNotification(String content) {
        try {
            Intent notificationIntent = new Intent(this, MainActivity.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(
                this, 0, notificationIntent,
                PendingIntent.FLAG_IMMUTABLE
            );
            
            // 使用系统默认图标，避免自定义图标问题
            int iconResId = android.R.drawable.ic_dialog_info;
            
            return new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("智能翻译器")
                .setContentText(content)
                .setSmallIcon(iconResId)
                .setContentIntent(pendingIntent)
                .setOngoing(true)
                .setSilent(true)
                .setPriority(NotificationCompat.PRIORITY_LOW)
                .build();
                
        } catch (Exception e) {
            Log.e(TAG, "创建通知失败，使用默认通知", e);
            // 如果创建通知失败，返回一个最简单的通知
            return new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("智能翻译器")
                .setContentText(content)
                .setSmallIcon(android.R.drawable.ic_dialog_info)
                .setPriority(NotificationCompat.PRIORITY_LOW)
                .build();
        }
    }

    /**
     * 创建一个简单的通知，用于快速启动
     */
    private Notification createSimpleNotification(String content) {
        try {
            // 使用最简单的通知，避免任何可能的阻塞操作
            return new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("智能翻译器")
                .setContentText(content)
                .setSmallIcon(android.R.drawable.ic_dialog_info)
                .setPriority(NotificationCompat.PRIORITY_LOW)
                .build();
        } catch (Exception e) {
            Log.e(TAG, "创建简单通知失败", e);
            // 如果连简单通知都创建失败，返回一个最基本的通知
            return new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("智能翻译器")
                .setContentText(content)
                .setSmallIcon(android.R.drawable.ic_dialog_info)
                .setPriority(NotificationCompat.PRIORITY_LOW)
                .build();
        }
    }
    
    /**
     * 更新通知内容
     */
    private void updateNotification(String content) {
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        if (notificationManager != null) {
            notificationManager.notify(NOTIFICATION_ID, createNotification(content));
        }
    }
    
    /**
     * 初始化Vosk识别器
     */
    private void initVoskRecognizer() {
        try {
            voskRecognizer = new VoskSpeechRecognizer(this);
            
            // 设置VAD回调
            voskRecognizer.setVadCallback(new VoskSpeechRecognizer.VadCallback() {
                @Override
                public void onVadSpeechStart() {
                    Log.d(TAG, "🎤 Vosk VAD检测到语音开始");
                    sendVoskVadStateBroadcast(true);
                    updateNotification("正在识别语音...");
                }
                
                @Override
                public void onVadSpeechEnd() {
                    Log.d(TAG, "🔇 Vosk VAD检测到语音结束");
                    sendVoskVadStateBroadcast(false);
                    updateNotification("Vosk语音识别服务运行中");
                }
                
                @Override
                public void onVadVoiceActivity(boolean isSpeech) {
                    // 实时语音活动状态
                    if (isSpeech) {
                        Log.d(TAG, "🎵 Vosk VAD检测到语音活动");
                    } else {
                        //Log.d(TAG, "🔇 Vosk VAD检测到静音");
                    }
                }
            });
            
            // 设置语音识别回调
            voskRecognizer.setSpeechRecognitionListener(new VoskSpeechRecognizer.SpeechRecognitionListener() {
                @Override
                public void onResult(String result) {
                    Log.d(TAG, "Vosk最终识别结果: " + result);
                    // 发送到悬浮窗，标记为Vosk结果
                    sendResultToFloatWindow(result, true, true);
                    updateNotification("识别完成: " + result);
                }
                
                @Override
                public void onPartialResult(String partialResult) {
                    Log.d(TAG, "Vosk部分识别结果: " + partialResult);
                    // 发送到悬浮窗，标记为Vosk结果
                    sendResultToFloatWindow(partialResult, false, true);
                    updateNotification("正在识别: " + partialResult);
                }
                
                @Override
                public void onError(String error) {
                    Log.e(TAG, "Vosk识别错误: " + error);
                    updateNotification("识别错误: " + error);
                }
                
                @Override
                public void onModelLoaded() {
                    Log.d(TAG, "Vosk模型加载完成");
                    isModelLoaded = true;
                    updateNotification("模型加载完成，开始识别");
                    autoStartRecognition();
                }
                
                @Override
                public void onModelLoadError(String error) {
                    Log.e(TAG, "Vosk模型加载失败: " + error);
                    isModelLoaded = false;
                    updateNotification("模型加载失败: " + error);
                }
            });
            
            Log.d(TAG, "✅ Vosk识别器初始化成功");
            
        } catch (Exception e) {
            Log.e(TAG, "❌ 初始化Vosk识别器失败", e);
            voskRecognizer = null;
            throw new RuntimeException("初始化Vosk识别器失败", e);
        }
    }
    
    /**
     * 发送Vosk VAD状态广播
     */
    private void sendVoskVadStateBroadcast(boolean isSpeaking) {
        try {
            Intent intent = new Intent("com.smart.translator.VOSK_VAD_STATE");
            intent.putExtra("is_speaking", isSpeaking);
            LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
            Log.d(TAG, "📡 发送Vosk VAD状态广播: " + (isSpeaking ? "说话中" : "静音"));
        } catch (Exception e) {
            Log.e(TAG, "发送Vosk VAD状态广播失败", e);
        }
    }
    
    /**
     * 注册TTS状态监听
     */
    private void registerTtsStateReceiver() {
        ttsStateReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if ("com.smart.translator.TTS_STATE_CHANGED".equals(intent.getAction())) {
                    boolean playing = intent.getBooleanExtra("is_playing", false);
                    isTtsPlaying = playing;
                    
                    if (playing) {
                        // TTS开始播放，暂停语音识别和VAD检测
                        Log.d(TAG, "🔊 TTS开始播放，暂停语音识别和VAD检测");
                        isVadEnabled = false; // 禁用VAD检测
                        
                        if (voskRecognizer != null) {
                            voskRecognizer.setVadEnabled(false); // 禁用Vosk的VAD检测
                        }
                        
                        if (voskRecognizer != null && isRecognitionStarted) {
                            voskRecognizer.stopRecognition();
                            isRecognitionStarted = false;
                            updateNotification("TTS播放中，暂停识别");
                        }
                        // 发送VAD结束广播，清除"正在说话"状态
                        sendVoskVadStateBroadcast(false);
                    } else {
                        // TTS结束播放，恢复语音识别
                        Log.d(TAG, "�� TTS结束播放，恢复语音识别");
                        
                        // 延迟500ms确保TTS音频完全播放完毕，避免残留影响VAD检测
                        new Handler(Looper.getMainLooper()).postDelayed(() -> {
                            isVadEnabled = true; // 恢复VAD检测
                            
                            if (voskRecognizer != null) {
                                // 重置VAD检测器，清除TTS音频残留状态
                                voskRecognizer.resetVadDetector();
                                voskRecognizer.setVadEnabled(true); // 恢复Vosk的VAD检测
                                Log.d(TAG, "🔄 延迟后恢复VAD检测");
                            }
                            
                            if (voskRecognizer != null && isModelLoaded && !isRecognitionStarted) {
                                voskRecognizer.startRecognition();
                                isRecognitionStarted = true;
                                updateNotification("Vosk语音识别服务运行中");
                            }
                        }, 500); // 延迟500ms
                    }
                }
            }
        };
        
        IntentFilter filter = new IntentFilter("com.smart.translator.TTS_STATE_CHANGED");
        LocalBroadcastManager.getInstance(this).registerReceiver(ttsStateReceiver, filter);
        Log.d(TAG, "📡 TTS状态监听器已注册");
    }
    
    /**
     * 自动加载模型
     */
    private void autoLoadModel() {
        Log.d(TAG, "开始自动加载Vosk模型");
        updateNotification("正在加载语音模型...");
        
        // 检测可用的模型文件
        try {
            String[] assets = getAssets().list("");
            boolean smallZipExists = false;
            boolean smallFolderExists = false;
            boolean fullZipExists = false;
            boolean fullFolderExists = false;
            
            for (String asset : assets) {
                if (asset.equals(SMALL_MODEL_ZIP_PATH)) {
                    smallZipExists = true;
                    Log.d(TAG, "找到小型模型zip文件: " + asset);
                } else if (asset.equals(SMALL_MODEL_PATH)) {
                    smallFolderExists = true;
                    Log.d(TAG, "找到小型模型文件夹: " + asset);
                } else if (asset.equals(MODEL_ZIP_PATH)) {
                    fullZipExists = true;
                    Log.d(TAG, "找到完整模型zip文件: " + asset);
                } else if (asset.equals(MODEL_PATH)) {
                    fullFolderExists = true;
                    Log.d(TAG, "找到完整模型文件夹: " + asset);
                }
            }
            
            // 优先使用小型模型以避免内存问题
            String modelPath = null;
            if (smallZipExists) {
                modelPath = SMALL_MODEL_ZIP_PATH;
                Log.d(TAG, "使用小型模型zip文件: " + modelPath);
            } else if (smallFolderExists) {
                modelPath = SMALL_MODEL_PATH;
                Log.d(TAG, "使用小型模型文件夹: " + modelPath);
            } else if (fullZipExists) {
                modelPath = MODEL_ZIP_PATH;
                Log.d(TAG, "使用完整模型zip文件: " + modelPath);
            } else if (fullFolderExists) {
                modelPath = MODEL_PATH;
                Log.d(TAG, "使用完整模型文件夹: " + modelPath);
            } else {
                Log.e(TAG, "未找到任何Vosk模型文件");
                updateNotification("未找到语音模型文件");
                return;
            }
            
            // 加载模型
            voskRecognizer.loadModel(modelPath);
            
        } catch (Exception e) {
            Log.e(TAG, "检查Vosk模型文件失败", e);
            updateNotification("模型文件检查失败");
        }
    }
    
    /**
     * 自动开始识别
     */
    private void autoStartRecognition() {
        if (isModelLoaded && !isRecognitionStarted) {
            Log.d(TAG, "自动开始Vosk语音识别");
            
            // 检查录音权限
            if (android.content.pm.PackageManager.PERMISSION_GRANTED != 
                getPackageManager().checkPermission(android.Manifest.permission.RECORD_AUDIO, getPackageName())) {
                Log.w(TAG, "没有录音权限，无法开始语音识别");
                updateNotification("没有录音权限");
                return;
            }
            
            // 设置音频源为手机麦克风
            voskRecognizer.setAudioSource(VoskSpeechRecognizer.AUDIO_SOURCE_MIC);
            Log.d(TAG, "设置音频源: 手机麦克风");
            
            try {
                voskRecognizer.startRecognition();
                isRecognitionStarted = true;
                updateNotification("Vosk语音识别已启动");
                Log.d(TAG, "Vosk语音识别启动成功");
            } catch (Exception e) {
                Log.e(TAG, "启动Vosk语音识别失败", e);
                updateNotification("启动识别失败: " + e.getMessage());
            }
        }
    }
    
    /**
     * 发送识别结果到悬浮窗
     */
    private void sendResultToFloatWindow(String text, boolean isFinal, boolean isVosk) {
        try {
            Intent intent = new Intent("com.smart.translator.ASR_RESULT");
            intent.putExtra("asr_text", text);
            intent.putExtra("is_vad_final", isFinal);
            intent.putExtra("is_vosk", isVosk); // 标记为Vosk结果
            LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
            Log.d(TAG, "发送Vosk结果到悬浮窗: " + text + (isFinal ? " (最终)" : " (部分)"));
        } catch (Exception e) {
            Log.e(TAG, "发送Vosk结果到悬浮窗失败", e);
        }
    }
    
    /**
     * 停止识别
     */
    public void stopRecognition() {
        if (voskRecognizer != null && isRecognitionStarted) {
            Log.d(TAG, "停止Vosk语音识别");
            voskRecognizer.stopRecognition();
            isRecognitionStarted = false;
            updateNotification("Vosk语音识别已停止");
        }
    }
    
    /**
     * 重新开始识别
     */
    public void restartRecognition() {
        if (voskRecognizer != null && isModelLoaded) {
            Log.d(TAG, "重新开始Vosk语音识别");
            try {
                voskRecognizer.startRecognition();
                isRecognitionStarted = true;
                updateNotification("Vosk语音识别已重启");
            } catch (Exception e) {
                Log.e(TAG, "重启Vosk语音识别失败", e);
                updateNotification("重启识别失败: " + e.getMessage());
            }
        }
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "VoskSpeechService onDestroy");
        
        // 注销TTS状态监听
        if (ttsStateReceiver != null) {
            try {
                LocalBroadcastManager.getInstance(this).unregisterReceiver(ttsStateReceiver);
                Log.d(TAG, "TTS状态监听器已注销");
            } catch (Exception e) {
                Log.e(TAG, "注销TTS状态监听器失败", e);
            }
            ttsStateReceiver = null;
        }
        
        if (voskRecognizer != null) {
            voskRecognizer.release();
            voskRecognizer = null;
        }
        
        isModelLoaded = false;
        isRecognitionStarted = false;

        if (vadAudioSourceReceiver != null) {
            try {
                LocalBroadcastManager.getInstance(this).unregisterReceiver(vadAudioSourceReceiver);
            } catch (Exception e) {
                Log.e(TAG, "注销VAD音源切换广播失败", e);
            }
            vadAudioSourceReceiver = null;
        }
    }
    
    /**
     * 检查服务是否正在运行
     */
    public static boolean isServiceRunning(Context context) {
        android.app.ActivityManager manager = (android.app.ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (android.app.ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (VoskSpeechService.class.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }
    
    /**
     * 获取服务状态信息
     */
    public String getServiceStatus() {
        return "模型加载: " + isModelLoaded + ", 识别运行: " + isRecognitionStarted;
    }
} 